package com.wan.net.core.packet;

import io.netty.buffer.ByteBuf;
/**
 * @author wwh
 * @date 2022/6/15 14:57
 */
public class Packet {
    /** 消息Id */
    private int messageId;
    /** 协议包体 */
    private byte[] content;

    public int getMessageId() {
        return messageId;
    }

    public void setMessageId(int messageId) {
        this.messageId = messageId;
    }

    public byte[] getContent() {
        return content;
    }

    public void setContent(byte[] content) {
        this.content = content;
    }

    public void write(ByteBuf byteBuf){
        byteBuf.writeInt(messageId);
        byteBuf.writeInt(content.length);
        byteBuf.writeBytes(content);
    }

    /**
     * 消息id|内容长度|数据  |
     *   4  |  4    |  n  |
     */
    public boolean read(ByteBuf byteBuf){
        //消息头长度不足，不读取
        if(byteBuf.readableBytes() < 8){
            return false;
        }
        //下标标记
        byteBuf.markReaderIndex();
        this.messageId = byteBuf.readInt();
        int length = byteBuf.readInt();
        //内容长度不足，重置读下标到标记点
        if(byteBuf.readableBytes() < length){
            byteBuf.resetReaderIndex();
            return false;
        }
        this.content = new byte[length];
        byteBuf.readBytes(content);
        return true;
    }
}
